package com.hitqz.robot.strategy;

import com.google.common.util.concurrent.RateLimiter;
import com.hitqz.robot.dto.JackDistanceDto;
import com.hitqz.robot.netty.message.ChipMessage;
import com.hitqz.robot.util.ChipCacheUtil;
import com.hitqz.robot.util.ChipToolKit;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xupkun
 * @date 2024/11/3
 */
@Slf4j
public class Chip1FStrategy implements ChipMessageHandlerStrategy {


    private static final RateLimiter logLimiter = RateLimiter.create(1);

    @Override
    public void handle(ChannelHandlerContext ctx, ChipMessage message) {
        InetSocketAddress ipSocket = (InetSocketAddress)ctx.channel().remoteAddress();
        String ipAddress = ipSocket.getAddress().getHostAddress();
        byte[] data = message.getData();
        byte mainCmd = data[0];
        byte subCmd = data[1];
        // 分配 ByteBuf 并将数据写入
        ByteBuf buffer = ctx.alloc().buffer(data.length);
        buffer.writeBytes(data);
        try {
            mainCmd = buffer.readByte();
            subCmd = buffer.readByte();
            if (subCmd == 0x01) {
                Map<String ,Object> ret = (Map<String, Object>) ChipCacheUtil.get(ChipCacheUtil.KEY_JACK_DISTANCE);
                if (ret  == null) {
                    ret = new HashMap<>();
                }
                // 设置结果
                int result = buffer.readByte();
                // 电机编号
                int sn = buffer.readByte();
                if (sn == 0x09) {
                    //命令编号
                    byte cmdSn = buffer.readByte();
                    int motorStatus = buffer.readByte();;
                    int jackDistance = buffer.readIntLE();
                    JackDistanceDto jackDistanceDto = JackDistanceDto.builder()
                            .status(motorStatus)
                            .jackDistance(jackDistance)
                            .build();
                    ret.put(ipAddress, jackDistanceDto);
                    ChipCacheUtil.put(ChipCacheUtil.KEY_JACK_DISTANCE, ret);
                }


                // todo 报警
            }
            ChipToolKit.release(message, true, true);
        } catch (Exception e) {
            log.error("[chip]deal  {}{}-message error,{}",String.format("%02x",mainCmd),String.format("%02x",subCmd),e.getMessage());
        } finally {
            // 确保 ByteBuf 在使用完后释放，防止内存泄漏
            buffer.release();
        }


    }
}

